﻿using AutoMapper;
using MediatR;
using Reporting.API.Application.Commands.ForeignKey;
using Reporting.Domain.ForeignKey;
using Reporting.Errorcode.ErrorCode;
using Reporting.Infrastructure.Interfaces.Payees;

namespace Reporting.API.Application.CommandHandler.ForeignKey
{
    /// <summary>
    /// 开、收票方
    /// </summary>
    public class PayeeCommondHandler : IRequestHandler<PayeeCommond, ApiResult<IList<Payee>>>
    {

        private readonly IPayeeRepository  _payeeRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<PayeeCommondHandler> _logger;

        public PayeeCommondHandler(ILogger<PayeeCommondHandler> logger, IMapper mapper, IPayeeRepository payeeRepository)
        {
            _logger = logger;
            _mapper = mapper;
            _payeeRepository = payeeRepository;
        }

        public async Task<ApiResult<IList<Payee>>> Handle(PayeeCommond request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取所有
                var Payees = await _payeeRepository.GetAllAsync();

                var result = _mapper.Map<IList<Payee>>(Payees);

                // 返回成功结果
                return ApiResult<IList<Payee>>.Success(result, StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {

                // 返回失败结果
                return ApiResult<IList<Payee>>.Fail("查询失败：" + ex.Message, StatusCodeEnum.BadRequest);
            }
        }
    }
}
